package com.activities;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;
import com.Adapters.PostAdapter;
import com.Adapters.Items.ItemPost;
import com.Adapters.Items.ItemPostPicture;
import com.Adapters.Items.RowType;
import com.Animations.AnimUtil;
import com.Animations.AnimationLists;
import com.Data.Albums.onDeleteCompleted;
import com.Data.Post;
import com.Data.Post.OnGetPicturesCompleted;
import com.Managers.FragmentManagerClass;
import com.Managers.UserManagerClass;
import com.PopUps.PopUpClass;
import com.SoapClasses.SoapUtil;
import com.UtilDate.UtilDate;
import com.shareup.R;


public class FragmentExploreAlbum extends Fragment implements DefaultFunctions {

    public static final int delayTime = 1000;

    public ListView listview;

    public boolean wasUpdate;

    private PostAdapter adapter;

    private boolean loaded = false;

    private View pview;

    private TableRow table;

    private FrameLayout messageLoading;

    private boolean refreshing;

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.DefaultFunctions#clear()
     */
    @Override
    public void clear() {

        if (adapter != null) {
            adapter.clear();
            adapter.notifyDataSetChanged();
        }
        AnimationLists.displayedImages.clear();
        AnimationLists.displayedText.clear();

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.DefaultFunctions#contains(java.lang.Object)
     */
    @Override
    public boolean contains(int object) {

        for (int i = 0; i < adapter.getCount(); i++) {
            ItemPost p = adapter.getPost(i);
            if (p.getPostId() == object)
                return true;

        }

        return false;

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#getParentActivity()
     */
    @Override
    public Activity getParentActivity() {

        return getActivity();
    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.DefaultFunctions#Init()
     */
    @Override
    public void Init() {

        if (!loaded) {
            if (UserManagerClass.UserLogged != null) {
                listview = (ListView) pview.findViewById(R.id.grid_main);
                adapter = new PostAdapter(this, getActivity(), R.layout.item_post_picture);
                listview.setAdapter(adapter);
                listview.setOnScrollListener(adapter);
                loaded = true;
            }
        }
    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.DefaultFunctions#loadFrom(int)
     */
    @Override
    public void loadFrom(int SoapUtilMode, int index) {

        Post getPic = new Post(index, 0, getActivity(), SoapUtilMode, "", new OnGetPicturesCompleted() {

            @Override
            public void Completed(Post[] result) {

                resultList(result);

            }
        });
        setLoading();
        delayTask(getPic);

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.DefaultFunctions#loadFromTags(java.lang.String)
     */
    @Override
    public void loadFromTags(String tag) {

        Post getPic = new Post(adapter.getCount(), 0, getActivity(), SoapUtil.MODE_TAGS, tag, new OnGetPicturesCompleted() {

            @Override
            public void Completed(Post[] result) {

                resultList(result);

            }
        });
        setLoading();
        delayTask(getPic);

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.DefaultFunctions#onConnection()
     */
    @Override
    public void onConnection() {

        AnimUtil.animatePopUp(table, false, null);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        FragmentManagerClass.aExploreAlbum = this;
        // |
        pview = inflater.inflate(R.layout.activity_explore, null);
        //
        messageLoading = (FrameLayout) inflater.inflate(R.layout.item_loading, null);
        //
        table = (TableRow) pview.findViewById(R.id.aExplore_table_tooltip);
        //
        Init();
        //
        return pview;

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.DefaultFunctions#onNoConnection()
     */
    @Override
    public void onNoConnection() {

        if (table.getChildCount() != 0) {
            table.removeAllViews();
        }
        String message = getActivity().getResources().getString(R.string.error_no_connection_message);
        PopUpClass up = new PopUpClass(getActivity());
        up.setMessage(message, R.drawable.connection_error, table);

    }

    @Override
    public void refresh() {

        refreshing = true;
        this.loadFrom(SoapUtil.MENU_VIEW, 0);
    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#remove(java.lang.Object)
     */
    @Override
    public void remove(Object object) {

        for (int i = 0; i < adapter.getCount(); i++) {
            ItemPost p = adapter.getPost(i);
            if (((Post) object).getID() == p.getPostId()) {
                adapter.remove(((Post) object));
                adapter.notifyDataSetChanged();
            }
        }
        if (adapter.getCount() == 0)
            setNoItemsMessage();

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.DefaultFunctions#resultList(java.lang.Object[])
     */
    @Override
    public void resultList(Object[] result) {

        boolean changes = false;
        for (Post p : (Post[]) result) {
            if (!contains(p.getID())) {
                if (refreshing)
                    adapter.addAt(p, 0);
                else
                    adapter.add(p);
                changes = true;
            }

        }
        if (changes)
            adapter.notifyDataSetChanged();

        refreshing = false;

        this.stopLoading();

        if (adapter.getCount() == 0)
            setNoItemsMessage();

    }

    @Override
    public void setLoading() {

        if (table.getChildCount() != 0) {
            table.removeAllViews();
        }
        table.addView(messageLoading);
        AnimUtil.animatePopUp(table, true, null);
    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.DefaultFunctions#setMessage(java.lang.String,
     * int)
     */
    @Override
    public void setMessage(String message, int iconResource) {

        new PopUpClass(getActivity()).setMessage(message, iconResource, table);

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#setNoItemsMessage()
     */
    @Override
    public void setNoItemsMessage() {

        try {

            this.setMessage(getActivity().getString(R.string.dialog_no_albums_explore), R.drawable.album_pressed);

        }
        catch (Exception x) {
            Log.e("FEXPLOREALBUM_SETNOITEMS", "ARREGLAR ESTO");
        }

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.DefaultFunctions#stopLoading()
     */
    @Override
    public void stopLoading() {

        AnimUtil.animatePopUp(table, false, null);

    }

    @Override
    public void updateComments(int idPicture, int count) {

        for (int i = 0; i < adapter.getCount(); i++) {
            ItemPost p = adapter.getPost(i);
            if (p.getPostId() == idPicture)
                p.setCommentsCount(count);

        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void updateLikes(int idPicture, int count) {

        for (int i = 0; i < adapter.getCount(); i++) {
            ItemPost p = adapter.getPost(i);
            if (p.getPostId() == idPicture)
                p.setLikesCount(count);

        }
        adapter.notifyDataSetChanged();
    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#updatePermissions(int, int)
     */
    @Override
    public void updatePermissions(int id, int newPermissions) {

        for (int i = 0; i < adapter.getCount(); i++) {
            ItemPost p = adapter.getPost(i);
            // IF ITS TYPE PICTURE
            if (p.getViewType() == RowType.PICTURE_POST.ordinal()) {
                ItemPostPicture pic = ((ItemPostPicture) p);
                if (pic.getPicture().getUser().getID() != UserManagerClass.UserLogged.getID()) {
                    if (id == pic.getPicture().getUser().getID()) {
                        pic.getPicture().setPermission(newPermissions);
                        pic.setOwnerShip();

                    }
                }
                else
                    break;

            }
        }

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#updateTime(int)
     */
    @Override
    public void updateTime(int id) {

        for (int i = 0; i < adapter.getCount(); i++) {

            ItemPost p = adapter.getPost(i);

            if (id == p.getPostId()) {
                View v = listview.getChildAt(i);
                TextView date = (TextView) v.findViewById(R.id.user_date);
                UtilDate dt = new UtilDate(v.getContext());
                dt.setTimeDifference(p.getPublicationDate(), date);
            }
        }

    }

    private void delayTask(final Post pictures) {

        Handler myHandler = new Handler();
        myHandler.postDelayed(new Runnable() {

            @Override
            public void run() {

                pictures.execute();
            }
            //
        }, delayTime);
    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#remove(java.lang.Object,
     * com.Data.Albums.onDeleteCompleted)
     */
    @Override
    public void remove(Object object, onDeleteCompleted callback) {

        // TODO Auto-generated method stub

    }
}
